package io.github.erehmi.library.vkb;

import android.content.Context;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout.LayoutParams;

import io.github.erehmi.library.util.SoftKeyboardCompat;

/**
 * @author WhatsAndroid
 */
public class LinearLayoutManager extends VirtualKeyboardController.LayoutManager {
    private static final String TAG = "LinearLayoutManager";

    private SoftKeyboardCompat mSoftKeyboardCompat;

    public LinearLayoutManager(Context context, SoftKeyboardCompat softKeyboardCompat) {
        super(context);
        mSoftKeyboardCompat = softKeyboardCompat;
    }

    @Override
    protected int getVirtualKeyboardSuggestedHeight() {
        return mSoftKeyboardCompat.getSuggestedHeight(getFocusView());
    }

    @Override
    protected void onVirtualKeyboardViewShow() {
        final View anchorView = getAnchorView();
        LayoutParams layoutParams = (LayoutParams) anchorView.getLayoutParams();
        int contentHeight = anchorView.getHeight();
        layoutParams.height = contentHeight;
        if (shouldAdjustContentHeight()) {
            layoutParams.height -= getVirtualKeyboardExpectedHeight();
        }
        Log.d(TAG, "contentHeight: " + contentHeight + ", " + "height: " + layoutParams.height);
        anchorView.setLayoutParams(layoutParams);
    }

    private boolean shouldAdjustContentHeight() {
        final View focusView = getFocusView();
        if (mSoftKeyboardCompat.isShown(focusView)) {
            return false;
        }

        final View anchorView = getAnchorView();
        Rect r = new Rect();
        anchorView.getWindowVisibleDisplayFrame(r);

        int[] location = new int[2];
        anchorView.getLocationOnScreen(location);

        return (r.bottom == location[1] + anchorView.getHeight());
    }

    @Override
    protected void onVirtualKeyboardViewHide() {
        final View anchorView = getAnchorView();
        LayoutParams layoutParams = (LayoutParams) anchorView.getLayoutParams();
        layoutParams.height = LayoutParams.MATCH_PARENT;
    }
}
